<?php
namespace Home\Controller;

class CartController extends CommonController {
	//展示购物车信息
	public function index(){
		
        $cart = $_SESSION['cart'];
        $cart1['total']=0;
        foreach($cart as $key=>$value){
            $cart1['total']+=$value['total'];
        }
		
		$this->assign('cart',$cart);
		$this->assign('cart1',$cart1);
		$this->display();
	}

	//用户点击购买或加入购物车时触发的操作
	//通过获取商品的id得到商品的信息，并将需要显示的信息放入session中
	public function add(){
		$id = $_GET['id'];
		$goods = D('Goods');
		$result = $goods->where('id='.$id)->find();
		$good['id']=$result['id'];
		$good['goods']=$result['goods'];
		$good['picname']=$result['picname'];
		$good['price']=$result['price'];
		$good['num'] = 1;
		//判断购物车是否有商品
		if(isset($_SESSION['cart'][$id])){
			$_SESSION['cart'][$id]['num'] += 1;
			$_SESSION['cart'][$id]['total']+=$_SESSION['cart'][$id]['num']*$_SESSION['cart'][$id]['price'];
		}else{
			
			$_SESSION['cart'][$id] = $good;
			$_SESSION['cart'][$id]['total']=$_SESSION['cart'][$id]['num']*$_SESSION['cart'][$id]['price'];
		}
		
		//添加商品成功后跳转到次页面
		$this->redirect('index');
		
	}
	//对购物车中商品的购买数量进行操作
	public function num(){

		$number = $_GET['number'];
		$id = $_GET['id'];
		$_SESSION['cart'][$id]['num'] += $number;
		if($_SESSION['cart'][$id]['num']<1){
			$_SESSION['cart'][$id]['num']=1;
		}
        $_SESSION['cart'][$id]['total']=$_SESSION['cart'][$id]['num']*$_SESSION['cart'][$id]['price'];
		$this->redirect('index');
	
	}
	//删除单独行的商品
	public function del(){
		$id = $_GET['id'];
		unset($_SESSION['cart'][$id]);
		$this->redirect('index');
	}
	//清空购物车里所有商品
	public function delAll(){
		// $id = $_GET['id'];
		unset($_SESSION['cart']);
		$this->redirect('index');
	}
	
}